package com.yearner.reviewplan.user;

import com.google.gson.JsonObject;
import com.yearner.reviewplan.common.aspect.AuthTokenV1;
import com.yearner.reviewplan.common.aspect.WebLog;
import com.yearner.reviewplan.common.enums.Consts;
import com.yearner.reviewplan.common.model.Result;
import com.yearner.reviewplan.common.model.Token;
import com.yearner.reviewplan.user.commands.ChangeCycleCommand;
import com.yearner.reviewplan.user.commands.ChangePasswordCommand;
import com.yearner.reviewplan.user.commands.LoginAccountCommand;
import com.yearner.reviewplan.user.commands.RegisterUserAccountCommand;
import com.yearner.reviewplan.user.data.Identification;
import com.yearner.reviewplan.user.data.IdentificationSession;
import com.yearner.reviewplan.user.enums.UserRepresentationEnum;
import com.yearner.reviewplan.user.exceptions.UserNotFoundException;
import com.yearner.reviewplan.user.model.User;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Optional;

import static com.yearner.reviewplan.user.enums.UserRepresentationEnum.userId;

/**
 * @author pengyg
 * @since 2019/10/16
 */
@Api
@RestController
@RequestMapping("/api/user")
public class UserController {
    private final UserApplicationService applicationService;
    private final UserRepresentation representation;
    private final Identification identification;
    private final IdentificationSession iSession;

    public UserController(UserApplicationService applicationService, UserRepresentation representation,
                          Identification identification, IdentificationSession identificationSession) {
        this.applicationService = applicationService;
        this.representation = representation;
        this.identification = identification;
        this.iSession = identificationSession;
    }

    @WebLog(description = "login")
    @PostMapping("login")
    public Result<Object> userLogin(@RequestBody LoginAccountCommand command, HttpServletRequest request) {
        iSession.checkFailedCount(request);
        User u = representation.login(command.getAccountName(), command.getPassword());
        if (u == null) {
            iSession.addFailedCount(request);
            throw new UserNotFoundException();
        }

        String token = Optional.ofNullable(identification.getToken(u.getUserId().toString()))
                        .orElseGet(()->identification.newToken(u));
        u.setPassword(null);
        return Result.success("登录成功", Token.of(u.getUserId(), token,u.getAccountName()));
    }

    @WebLog
    @PostMapping("register")
    public Result<Object> register(@RequestBody RegisterUserAccountCommand command) {
        User user = applicationService.register(command);
        String token = identification.newToken(user);
        return Result.success("注册成功！", Token.of(user.getUserId(), token,user.getAccountName()));
    }

    @WebLog
    @AuthTokenV1
    @PostMapping("getDetail")
    public Result<Object> getUserDetail(HttpServletRequest request) {
        User user = identification.getUserById(request.getAttribute(Consts.CURRENT_USER_ID).toString());
        user.setPassword(null);
        return Result.success(user);
    }

    @WebLog
    @AuthTokenV1
    @PostMapping("changePassword")
    public Result<Object> changePassword(@RequestBody ChangePasswordCommand command, HttpSession session, HttpServletRequest request) {
        if (!identification.authUserId(command.getUserId(),request)) {
            command.setUserId(request.getAttribute(Consts.CURRENT_USER_ID).toString());
        }
        User user = applicationService.changePassword(command);
        String newToken = identification.changeToken(user, session);
        return Result.success("密码修改成功！", Token.of(user.getUserId(), newToken,user.getAccountName()));
    }

    @WebLog
    @AuthTokenV1
    @PostMapping("changeCycle")
    public Result<String> changeCycle(@RequestBody ChangeCycleCommand command, HttpServletRequest request) {
        String userId = request.getAttribute(Consts.CURRENT_USER_ID).toString();
        applicationService.changeCycle(command.getCycle(), userId);
        return Result.success();
    }


}
